<template>
    <div>
        <el-form :inline="true" :model="query" class="query-form" size="small">
            <el-form-item>
                <el-button type="primary" icon="el-icon-edit" @click.native="handleForm(null,null)">添加</el-button>
            </el-form-item>
            <el-form-item class="query-form-item">
                <el-tag>创建时间</el-tag>
            </el-form-item>

            <el-form-item>
                <el-date-picker
                    v-model="createTime"
                    type="datetimerange"
                    :picker-options="pickerOptions"
                    range-separator="-"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                    align="left"
                    format="yyyy-MM-dd HH:mm:ss"
                    value-format="yyyy-MM-dd HH:mm:ss"
                    :default-time="['00:00:00','23:59:59']"
                    @change="dateChange"
                ></el-date-picker>
            </el-form-item>
        </el-form>

        <el-table
            ref="multipleTable"
            v-loading="loading"
            :data="list"
            :header-cell-style="{background:'#F4F4F5',color:'#606266'}"
            @selection-change="handleSelectionChange"
            border
        >
            <el-table-column
                label="选择"
                prop="problemid"
                type="selection"
                :show-overflow-tooltip="true"
                width="50"
                align="center"
            />
            <el-table-column label="序号" align="center" width="50" prop="problemid">
            </el-table-column>

            <el-table-column label="问题" align="center" width="600" prop="problemtitle">
            </el-table-column>

            <el-table-column label="创建时间" :show-overflow-tooltip="true" align="center">
                <template slot-scope="scope">
                    <i class="el-icon-time"></i>
                    <span>{{ scope.row.createtime | formatDateStr('yyyy-MM-dd hh:mm:ss') }}</span>
                </template>
            </el-table-column>

            <el-table-column width="500" label="操作" align="center" >
                <template slot-scope="scope">
                    <el-button type="primary" size="mini" @click.native="handleLook(scope.$index,scope.row)">查看</el-button>
                    <el-button type="danger" size="mini" @click.native="handleDel(scope.row.problemid)">删除</el-button>
                </template>
            </el-table-column>

        </el-table>

        <div class="left-container">
            <el-button type="danger" size="small" @click="delGroup()">删除已选</el-button>
            <transition name="el-fade-in-linear">
                <el-button size="small" @click="toggleSelection()" v-show="cancelToggle">取消选择</el-button>
            </transition>
        </div>
        <el-pagination
            class="pagination-container"
            background
            :page-size="query.pageSize"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            layout="total,sizes,prev, pager, next, jumper"
            :page-sizes="[10, 20, 30, 50]"
            :total="totalNumber"
        ></el-pagination>
        <!-- </el-scrollbar> -->
        <!--add表单-->
        <el-dialog
            :title="formMap[formName]"
            :visible.sync="formVisible"
            :before-close="hideForm"
            width="800px"
            top="5vh"
            v-dialogDrag
        >
            <el-form :model="formData" :rules="formRules" ref="dataForm" >
                <el-form-item label="帮助问题:" prop="problemtitle" >
                    <el-input v-model="formData.problemtitle" placeholder="请输入问题" clearable></el-input>
                </el-form-item>

                <el-form-item label="解答:" prop="problemanswer">
                    <tinymce
                        style="display: inline-block;width: 100%;"
                        ref="tinymce"
                        :height="300"
                        v-model="formData.problemanswer"
                    />
                </el-form-item>

            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click.native="formSubmit()" :loading="formLoading">保存</el-button>
                <el-button @click.native="hideForm">返回</el-button>
            </div>
        </el-dialog>
<!--查看表单-->
        <el-dialog
            :title="formMap[formName]"
            :visible.sync="formLook"
            :before-close="hideLook"
            width="800px"
            top="5vh"
            v-dialogDrag
        >
            <el-form :model="formData" :rules="formRules" ref="dataForm" >
                <el-form-item label="帮助问题：">
                    <input v-model="formData.problemtitle" type="text" readonly>
                </el-form-item>

                <el-form-item label="解答：">
                    <br>
                    <div v-html="formData.problemanswer"></div>
                </el-form-item>
            </el-form>
        </el-dialog>
    </div>
</template>

<script>
    import { getList,delproblem,addproblem} from "../../api/commonproblem/commonproblem";
    import Tinymce from "../../components/Tinymce/index.vue";
    const formJson = {
        problemtitle:"",
        problemid:"",
        problemanswer: "",
        createtime:"",
        isdel: "",
    };
    export default {
        data() {

            return {
                pickerOptions: {//快速选择日期
                    shortcuts: [
                        {
                            text: "最近一周",
                            onClick(picker) {
                                const end = new Date();
                                const start = new Date();
                                start.setTime(
                                    start.getTime() - 3600 * 1000 * 24 * 7
                                );
                                picker.$emit("pick", [start, end]);
                            }
                        },
                        {
                            text: "最近一个月",
                            onClick(picker) {
                                const end = new Date();
                                const start = new Date();
                                start.setTime(
                                    start.getTime() - 3600 * 1000 * 24 * 30
                                );
                                picker.$emit("pick", [start, end]);
                            }
                        },
                        {
                            text: "最近三个月",
                            onClick(picker) {
                                const end = new Date();
                                const start = new Date();
                                start.setTime(
                                    start.getTime() - 3600 * 1000 * 24 * 90
                                );
                                picker.$emit("pick", [start, end]);
                            }
                        },
                        {
                            text: "最近六个月",
                            onClick(picker) {
                                const end = new Date();
                                const start = new Date();
                                start.setTime(
                                    start.getTime() - 3600 * 1000 * 24 * 180
                                );
                                picker.$emit("pick", [start, end]);
                            }
                        }
                    ]
                },

                cancelToggle: false,
                createTime: [],
                query: {
                    problemid:"",
                    currentPage: 1,
                    pageSize: 10,
                    starttime: "",
                    endtime:""
                },
                list: [],
                totalNumber: 0,
                loading: true,
                index: null,
                formName: null,
                formMap: {
                    add: "添加",
                    edit: "编辑"
                },
                formLoading: false,
                formVisible: false,
                formLook:false,
                formData: formJson,
                formRules: {


                    problemanswer: {
                        required: true,
                        message: "请输入详情",
                        trigger: "blur"
                    },
                    problemtype: {
                        required: true,
                        message: "请选择类型",
                        trigger: "blur"
                    }

                },
                multipleSelection: [] //多选集合
            };
        },
        components: {
            Tinymce
        },
        methods: {
            dateChange(val) {
                if (val == null) {
                    this.query.starttime = "";
                    this.query.endtime = "";
                } else {
                    this.query.starttime = val[0];
                    this.query.endtime = val[1];
                }
                this.getList();
            },
            toggleSelection(rows) {
                if (rows) {
                    rows.forEach(row => {
                        this.$refs.multipleTable.toggleRowSelection(row);
                    });
                } else {
                    this.$refs.multipleTable.clearSelection();
                }
            },
            handleSelectionChange(val) {
                this.multipleSelection = val;
                if (val == "") {
                    this.cancelToggle = false;
                    return;
                }
                this.cancelToggle = true;
            },
            delGroup() {
                var ids = this.multipleSelection.map(item => item.problemid).join(); //获取所有选中行的id组成的字符串，以逗号分隔
                if (ids == "") {
                    this.$message({
                        message: "请先选择",
                        type: "warning"
                    });
                    return;
                }
                this.handleDel(ids);
            },
            onRest() {
                this.$router.push({
                    path: ""
                });
                this.query = {

                    currentPage: 1,
                    pageSize: 10
                };
                this.createTime = [];
                this.getList();
            },
            onSubmit() {
                this.$router.push({
                    path: "",
                    //query: this.query
                });
                this.getList();
            },
            handleCurrentChange(val) {
                this.query.currentPage = val;
                //scrollTo(0, 800);
                this.getList();
            },
            handleSizeChange(val) {
                this.query.pageSize = val;
                this.getList();
            },
            getList() {
                this.loading = true;
                getList(this.query)
                    .then(response => {
                        if (response.code) {
                            this.$message.error(response.message);
                        }

                        this.list = response.data.list || [];
                        this.totalNumber = response.data.totalNumber || 0;
                        setTimeout(() => {
                            this.loading = false;
                        }, 0.3 * 1000);
                    })
                    .catch(() => {
                        this.loading = false;
                        this.list = [];
                        this.totalNumber = 0;
                    });
            },
            // 隐藏表单
            hideForm() {
                // 更改值
                this.formVisible = !this.formVisible;
                // 清空表单
                this.$refs["dataForm"].resetFields();
                this.$refs.tinymce.clearContent();
                return true;
            },
            // 显示表单
            handleForm(index, row) {
                console.log(row)
                this.formVisible = true;
                this.formData = Object.assign({}, formJson);
                if (row !== null) {
                    this.formData = Object.assign({}, row);
                }
                this.formName = "add";
                //编辑
                if (index !== null) {
                    this.index = index;
                    this.formName = "edit";
                    let vm = this;
                    setTimeout(function() {
                        vm.$nextTick(() => {
                            if (vm.$refs.tinymce) {
                                vm.$refs.tinymce.setContent(
                                    vm.formData.problemanswer  //获取富文本内容
                                );
                            }
                        });
                    }, 350);
                }
                // 清空验证信息表单
                if (this.$refs["dataForm"]) {
                    this.$refs["dataForm"].clearValidate();
                }
            },
            hideLook() {
                // 更改值
                this.formLook = !this.formLook;
                // 清空表单
                this.$refs["dataForm"].resetFields();

                return true;
            },

            handleLook(index, row) {
                this.formLook = true;
                this.formData = Object.assign({}, formJson);
                if (row !== null) {
                    this.formData = Object.assign({}, row);
                }
            },
            formSubmit() {
                this.$refs["dataForm"].validate(valid => {
                    if (valid) {
                        this.formLoading = true;
                        let data = new URLSearchParams(this.formData);
                        addproblem(data).then(response => {
                            this.formLoading = false;
                            if (response.code) {
                                this.$message.error(response.message);
                                return false;
                            }
                            this.$message.success("操作成功");
                            // 刷新表单
                            this.$refs["dataForm"].resetFields();
                            this.$refs.tinymce.clearContent();
                            this.formVisible = false;
                            this.query.searchText="";
                            this.getList();
                        });
                    }
                });
            },
            // 删除
            handleDel(ids) {
                if (ids) {
                    this.$confirm("确认要删除吗?", "提示", {
                        type: "warning"
                    })
                        .then(() => {
                            this.loading = true;
                            var params = new URLSearchParams();
                            params.append("ids", ids);
                            delproblem(params)
                                .then(response => {
                                    this.loading = false;
                                    if (response.code) {
                                        this.$message.error(response.message);
                                        return false;
                                    }
                                    this.$message.success("删除成功");
                                    // 刷新数据
                                    //this.list.splice(index, 1);
                                    this.getList();
                                })
                                .catch(() => {
                                    this.loading = false;
                                });
                        })
                        .catch(() => {});
                }
            }
        },
        filters: {
            typeFilterType(status) {
                const statusMap = {
                    1: "warning"
                };
                return statusMap[status];
            },
            typeFilterName(status) {
                const statusMap = {
                    0: "常见",
                    1: "其他"
                };
                return statusMap[status];
            }
        },
        mounted() {},
        created() {
            // 将参数拷贝进查询对象
            let query = this.$route.query;
            this.query = Object.assign(this.query, query);
            this.query.pageSize = parseInt(this.query.pageSize);
            // 加载表格数据
            this.getList();
        }
    };
</script>

<style type="text/scss" lang="scss">
    body {
        margin: 0;
    }
</style>

